//
//  CAIPHPickerControllerManager.m
//  CAIImagePickerController_Example
//
//  Created by 海参 on 2022/7/14.
//  Copyright © 2022 海参. All rights reserved.
//

#import "CAIPHPickerControllerManager.h"

#import <MobileCoreServices/MobileCoreServices.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>

@implementation CAIPHPickerConfiguration

- (instancetype)init{
    self = [super init];
    if (self) {
        self.allowPickingImage = YES;
        self.allowPickingVideo = NO;
        self.selectionLimit = 1;
    }
    return self;
}

- (id)copyWithZone:(nullable NSZone *)zone{
    CAIPHPickerConfiguration *obj = [[[self class] allocWithZone:zone] init];
    return obj;
}

@end


@interface CAIPHPickerControllerManager()

@property (nonatomic, strong) PHPickerViewController *pickerViewController;

@property (nonatomic, strong) PHPickerConfiguration *configuration;
@end


@implementation CAIPHPickerControllerManager


- (void)dealloc{
    
}


- (void)setPickerConfiguration:(CAIPHPickerConfiguration *)pickerConfiguration{
    _pickerConfiguration = pickerConfiguration;
    
    if (!pickerConfiguration) {
        return;
    }
    self.configuration.selectionLimit = pickerConfiguration.selectionLimit;
    NSAssert(pickerConfiguration.allowPickingImage || pickerConfiguration.allowPickingVideo, @"必须选择照片或视频其一");

    if (pickerConfiguration.allowPickingImage && !pickerConfiguration.allowPickingVideo) {
        self.configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[[PHPickerFilter imagesFilter],[PHPickerFilter livePhotosFilter]]];

    }else if (!pickerConfiguration.allowPickingImage && pickerConfiguration.allowPickingVideo){
        self.configuration.filter = [PHPickerFilter videosFilter];
    }
    else{
        self.configuration.filter = [PHPickerFilter anyFilterMatchingSubfilters:@[[PHPickerFilter imagesFilter],[PHPickerFilter videosFilter],[PHPickerFilter livePhotosFilter]]];
    }
}

- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id)delegate
{
    [self showImagePickerWithFromViewController:viewController delegate:delegate configuraton:self.pickerConfiguration];
}



- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id)delegate
                               selectionLimit:(NSInteger)selectionLimit
                            allowPickingImage:(BOOL)allowPickingImage
                            allowPickingVideo:(BOOL)allowPickingVideo
{
    CAIPHPickerConfiguration *configuration = [CAIPHPickerConfiguration new];
    configuration.selectionLimit = selectionLimit;
    configuration.allowPickingImage = allowPickingImage;
    configuration.allowPickingVideo = allowPickingVideo;
    [self showImagePickerWithFromViewController:viewController delegate:delegate configuraton:configuration];
}


- (void)showImagePickerWithFromViewController:(UIViewController *)viewController
                                     delegate:(id)delegate
                                 configuraton:(nullable CAIPHPickerConfiguration *)configuration
{
    self.delegate = delegate;
    if (!configuration) {
        configuration = [CAIPHPickerConfiguration new];
    }
    self.pickerConfiguration = configuration;
    [viewController presentViewController:self.pickerViewController animated:YES completion:^{}];
}


///即使关闭权限访问，但依然可以访问选择
- (PHPickerViewController *)pickerViewController API_AVAILABLE(ios(14)){
    if (!_pickerViewController) {
        PHPickerViewController *vc = [[PHPickerViewController alloc] initWithConfiguration:self.configuration];
        vc.delegate = self;
        vc.modalPresentationStyle = UIModalPresentationFullScreen;
        _pickerViewController = vc;
    }
    return _pickerViewController;
}


- (PHPickerConfiguration *)configuration API_AVAILABLE(ios(14)){
    if (!_configuration) {
        PHPickerConfiguration *confg = [[PHPickerConfiguration alloc] init];
        confg.selectionLimit = 3;
        if (@available(iOS 15, *)) {
            confg.selection = PHPickerConfigurationSelectionOrdered;
        } else {
            // Fallback on earlier versions
        }
        PHPickerFilter *filter;
        filter = [PHPickerFilter imagesFilter];
        confg.filter = filter;
        _configuration = confg;
    }
    return _configuration;
}

- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (results.count ==0) {
        NSError *error = [CAIImagePickerManagerErrorConst errorWithCode:ImagePickerControllerErrorCodeCancel];
        if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingMediaWithPhotos:error:)]) {
            [self.delegate imagePickerControllerManager:self didFinishPickingMediaWithPhotos:nil error:error];
        }
    }
    else{
//        NSArray *supportedRepresentations = @[
//        UTTypeJPEG.identifier,
//        UTTypeTIFF.identifier,
//        UTTypeGIF.identifier,
//        UTTypePNG.identifier,
//        UTTypeICNS.identifier,
//        UTTypeBMP.identifier,
//        UTTypeICO.identifier,
//        UTTypeRAWImage.identifier,
//        UTTypeSVG.identifier,
//        UTTypeWebP.identifier,
//        UTTypeLivePhoto.identifier,
//        UTTypeHEIF.identifier,
//        UTTypeHEIC.identifier
//        ];
        
        NSMutableArray *imageMArr = [NSMutableArray array];
        __block NSInteger count = 0;
        for (PHPickerResult *result in results)
          {
              NSItemProvider *itemProvider = result.itemProvider;
              ///com.apple.quicktime-movie
              NSString *uti = [itemProvider.registeredTypeIdentifiers firstObject];
              NSLog(@"assetIdentifier:%@,type = %@",result.assetIdentifier,uti);
             // Get UIImage
//              if ([itemProvider canLoadObjectOfClass:[PHLivePhoto class]]) {
//                  count++;
//                  [itemProvider loadObjectOfClass:[PHLivePhoto class] completionHandler:^(__kindof id<NSItemProviderReading>  _Nullable object, NSError * _Nullable error) {
//
//                  }];
//              }
              if ([itemProvider canLoadObjectOfClass:[UIImage class]]) {
                  
                  __weak __typeof(&*self)weakSelf = self;
                  [itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(__kindof id<NSItemProviderReading>  _Nullable object, NSError * _Nullable error)
                  {
                      count++;
                     ///即使是同一图片/视频资源，每次选择返回也是不一样的内存地址；
                     if ([object isKindOfClass:[UIImage class]])
                     {
                         [imageMArr addObject:object];
                     }
                      if (count == results.count) {
                          dispatch_async(dispatch_get_main_queue(), ^{
                             NSLog(@"Selected image: %@", (UIImage*)object);
                              if ([weakSelf.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingMediaWithPhotos:error:)]) {
                                  [weakSelf.delegate imagePickerControllerManager:weakSelf didFinishPickingMediaWithPhotos:imageMArr error:nil];
                              }
                          });
                      }
                  }];
              }
              else{
                  count++;
                  if (count == results.count) {
                      dispatch_async(dispatch_get_main_queue(), ^{
                          if ([self.delegate respondsToSelector:@selector(imagePickerControllerManager:didFinishPickingMediaWithPhotos:error:)]) {
                              [self.delegate imagePickerControllerManager:self didFinishPickingMediaWithPhotos:imageMArr error:nil];
                          }
                      });
                  }
              }
       
          }
    }
    ///清除记忆选择的图片
    self.pickerViewController = nil;
}

@end


